import { login, logout, verificaCode, getAdminInfo } from '@/api/user'

const state = {
  loginState: false,
  adminInfo: {}
}

const mutations = {
  SET_ADMIN_INFO: (state, result) => {
    if (result) {
      state.adminInfo = result
      state.loginState = true
      return
    }
    state.adminInfo = {}
    state.loginState = false
  }
}

const actions = {
  // 用户登陆
  async login({ commit }, userInfo) {
    return await login(userInfo)
  },
  // 退出登陆
  async logout({ commit }) {
    await logout()
    commit('SET_ADMIN_INFO', false)
  },
  // 获取验证码
  async getVerificaCode({ commit }) {
    const { data } = await verificaCode({
      type: 'adminLogin'
    })
    return data
  },
  // 获取用户信息
  async getAdminInfo({ commit }) {
    const data = await getAdminInfo()
    if (data.code === 0) {
      commit('SET_ADMIN_INFO', data.data)
    } else {
      commit('SET_ADMIN_INFO', false)
    }
    return data
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
